# -*- coding: utf-8 -*-
import datetime
import hashlib
import json
import time
from collections import OrderedDict

import requests
from django.conf import settings

from async import async_job
from common.cache import redis_cache
from common.channel.pay import check_channel_order
from common.order.db import get_pay, add_pay_success
from common.order.model import PAY_STATUS
from common.utils import track_logging
from common.utils.exceptions import ParamError
from common.utils.ip_address import check_valid_ip_address

_LOGGER = track_logging.getLogger(__name__)

APP_CONF = {
    '966001806000137': {  # 远大_支付宝扫码H5_02
        'API_KEY': 'b5711ac693bef098b7bc0b58c74f3b81',
    },
    '966001806000138': {  # 远大_支付宝扫码
        'API_KEY': 'dbbbe4a2b682e1947b31f46bf1e01d39',
    },
    '966001806000139': {  # 远大_云闪付
        'API_KEY': '9ef8836e03223964798c01205406194d',
    },
    '966001806000140': {  # 远大_快捷
        'API_KEY': '0a8efbba764f36794c447a22039cc940',
    },
    '966001806000141': {  # 远大_微信扫码03
        'API_KEY': 'ffa57cb30259322da929c0196ceeccfa',
    },
    'gateway': 'http://47.254.56.192/powerpay-gateway-onl/txn',
}


# alipay_h5 	支付宝扫码H5
# alipay 	支付宝扫码
# unionpay 	云闪付
# quickpay 	快捷
# wechat 	微信扫码

def _get_pay_type(service):
    if service == 'alipay_h5':
        return '42'
    elif service == 'alipay':
        return '32'
    elif service == 'unionpay':
        return '23'
    elif service == 'quickpay':
        return '22'
    elif service == 'wechat':
        return '31'
    return '32'


def _get_api_key(mch_id):
    return APP_CONF[mch_id]['API_KEY']


def _get_gateway():
    return APP_CONF['gateway']


def _gen_sign(s):
    m = hashlib.md5()
    m.update(s.encode('utf-8'))
    sign = m.hexdigest().lower()
    return sign


def _get_device_ip(info):
    try:
        extra = json.loads(info['extra'])
    except:
        extra = {}
    user_info = extra.get('user_info', {})
    return user_info.get('device_ip') or '127.0.0.1'


def generate_verify_sign(parameter, key):
    s = ''
    for k, v in sorted(parameter.items()):
        s += '%s=%s&' % (k, v)
    s += 'k=%s' % key
    return _gen_sign(s)


def verify_notify_sign(params, key):
    sign = params['mac']
    params.pop('mac')
    calculated_sign = generate_verify_sign(params, key)
    if sign != calculated_sign:
        _LOGGER.info("majipay sign: %s, calculated sign: %s", sign, calculated_sign)
        raise ParamError('sign not pass, data: %s' % params)


# 扫码支付，快捷支付
def check_pay_type(parameter, ptype):
    parameter.pop('clientIp')
    parameter.pop('sceneBizType')
    parameter.pop('wapUrl')
    parameter.pop('wapName')
    parameter.pop('appName')
    parameter.pop('appPackage')
    if ptype == '23':  # 云闪付
        parameter.pop('productTitle')
    return parameter


def _build_form(params, gateway):
    html = u"<head><title>loading...</title></head><form id='submit' name='submit' action='" + gateway + "' method='post'>"
    for k, v in params.items():
        html += "<input type='hidden' name='%s' value='%s'/>" % (k, v)
    html += "</form>"
    html += "<script>doc" \
            "ument.forms['submit'].submit();</script>"
    return html


def create_charge(pay, pay_amount, info):
    app_id = info['app_id']
    service = info.get('service')
    api_key = _get_api_key(app_id)
    pay_type = str(_get_pay_type(service))
    tt = datetime.datetime.now() + datetime.timedelta(hours=8)
    # h5的请求报文，其余请求报文会相应减少，根据不同的支付方式做相应操作
    parameter_dict = OrderedDict((
        ('txnType', '01'),
        ('txnSubType', pay_type),
        ('secpVer', 'icp3-1.1'),
        ('secpMode', 'perm'),
        # 密钥编号，由平台提供，现与商户号相同
        ('macKeyId', app_id),
        ('orderDate', tt.strftime('%Y%m%d')),
        ('orderTime', tt.strftime('%H%M%S')),
        # 商户号
        ('merId', app_id),
        # 商户生成的订单号
        ('orderId', str(pay.id)),
        ('pageReturnUrl', '{}/pay/api/{}/majipay/'.format(
            settings.NOTIFY_PREFIX, settings.RETURN_PATH)),
        ('notifyUrl', '{}/pay/api/{}/majipay/{}'.format(
            settings.NOTIFY_PREFIX, settings.NOTIFY_PATH, app_id)),
        ('productTitle', 'none'),
        # 交易金额单位分
        ('txnAmt', str(int(pay_amount * 100))),
        # 交易币种
        ('currencyCode', '156'),
        ('clientIp', _get_device_ip(info)),
        # 场景业务类型  WAP|IOS_APP|ANDROID_APP
        ('sceneBizType', 'WAP'),
        ('wapUrl', 'http://test.com'),
        ('wapName', 'none'),
        ('appName', 'none'),
        ('appPackage', 'none'),
        ('timeStamp', tt.strftime('%Y%m%d%H%M%S')),
    ))
    # 获取其他支付方式的对应的请求数据
    if pay_type != '42':
        parameter_dict = check_pay_type(parameter_dict, pay_type)
    parameter_dict['mac'] = generate_verify_sign(parameter_dict, api_key)
    _LOGGER.info("majipay create date: %s, order_id is: %s", json.dumps(parameter_dict),
                 parameter_dict['orderId'])
    if pay_type in ('42', '32', '31'):
        headers = {'Content-Type': 'application/x-www-form-urlencoded'}
        response = requests.post(_get_gateway(), data=parameter_dict, headers=headers, timeout=5)
        _LOGGER.info("majipay response: %s", response)
    if pay_type == '42':
        resp_obj = json.loads(response.text)
        if resp_obj['txnStatus'] == '20' or resp_obj['txnStatus'] == '30':
            return {'charge_info': resp_obj['respMsg']}
        url = resp_obj['codePageUrl']
    elif pay_type == '32' or pay_type == '31':
        resp_obj = json.loads(response.text)
        if resp_obj['txnStatus'] == '20' or resp_obj['txnStatus'] == '30':
            return {'charge_info': resp_obj['respMsg']}
        url = resp_obj['codeImgUrl']
    else:
        html_text = _build_form(parameter_dict, _get_gateway())
        cache_id = redis_cache.save_html(pay.id, html_text)
        url = settings.PAY_CACHE_URL + cache_id
    _LOGGER.info('majipay url: %s', url)
    return {'charge_info': url}


# success异步回调
def check_notify_sign(request, app_id):
    _LOGGER.info("majipay notify body: %s", request.body)
    data = dict(request.POST.iteritems())
    _LOGGER.info("majipay notify data: %s, order_id is: %s", data, data['orderId'])
    verify_notify_sign(data, _get_api_key(app_id))
    pay_id = data['orderId']
    check_valid_ip_address(str(request.META['REMOTE_ADDR']), pay_id)
    if not pay_id:
        _LOGGER.error("fatal error, pay object not exists, data: %s" % data)
        raise ParamError('majipay event does not contain valid pay ID')
    pay = get_pay(pay_id)
    if not pay:
        raise ParamError('pay_id: %s invalid' % pay_id)
    if pay.status != PAY_STATUS.READY:
        raise ParamError('pay %s has been processed' % pay_id)

    mch_id = pay.mch_id
    trade_status = str(data['txnStatus'])
    trade_no = data['orderId']
    # 单位分转换为元
    total_fee = float(data['txnAmt']) / 100.0
    extend = {
        'trade_status': trade_status,
        'trade_no': trade_no,
        'total_fee': total_fee,
    }
    check_channel_order(pay_id, total_fee, app_id)

    if trade_status == '10':
        _LOGGER.info('majipay check order success, user_id:%s pay_id:%s' % (mch_id, pay_id))
        add_pay_success(mch_id, pay_id, total_fee, trade_no, extend)
        # async notify
        async_job.notify_mch(pay_id)


def query_charge(pay_order, app_id):
    pay_id = pay_order.id
    api_key = _get_api_key(app_id)
    pay = get_pay(pay_id)
    parameter_dict = OrderedDict((
        ('txnType', '00'),
        # 报文字类
        ('txnSubType', '10'),
        ('secpVer', 'icp3-1.1'),
        ('secpMode', 'perm'),
        # 密钥编号，由平台提供，现与商户号相同
        ('macKeyId', app_id),
        # 商户号
        ('merId', app_id),
        # 商户生成的订单号
        ('orderId', str(pay.id)),
        # 下单时间
        ('orderDate', str(pay.created_at)),
        ('timeStamp', time.strftime('%Y%m%d%H%M%S', time.localtime())),
    ))
    parameter_dict['mac'] = generate_verify_sign(parameter_dict, api_key)
    _LOGGER.info('majipay query data %s, order_id is: %s', json.dumps(parameter_dict),
                 parameter_dict['orderId'])
    headers = {'Content-Type': 'application/x-www-form-urlencoded'}
    response = requests.post(_get_gateway(), data=parameter_dict, headers=headers, timeout=5)
    data = json.loads(response.text)
    _LOGGER.info('majipay query rsp, %s', data)
    if response.status_code == 200:
        try:
            trade_status = data['txnStatus']
            total_fee = float(data.get('txnAmt')) / 100.0
            trade_no = str(data['orderId'])
            extend = {
                'trade_status': trade_status,
                'trade_no': trade_no,
                'total_fee': total_fee,
            }
            if trade_status == '10':
                check_channel_order(pay_id, total_fee, app_id)
                _LOGGER.info('majipay query order success, mch_id:%s pay_id:%s' % (pay_order.mch_id, pay_id))
                res = add_pay_success(pay_order.mch_id, pay_id, total_fee, trade_no, extend)
                if res:
                    async_job.notify_mch(pay_order.id)
            else:
                _LOGGER.info(
                    'majipay query order error, trade_status:%s error_message:%s' % (trade_status, data['respMsg']))
        except Exception as e:
            _LOGGER.info(
                'majipay query order success,but not pay success, error:%s, msg:%s ' % (e, data))
    else:
        _LOGGER.warn('majipay data error, status_code: %s', response.status_code)
